from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import auth


# Create your views here.

# def index(request):
#     return HttpResponse("Hello World!")

# 跳转至主页页面
def toIndex(request):
    return render(request, "index.html")


# 登陆方法
def toLogin(request):
    if request.method == 'POST':
        user_name = request.POST.get("userName")
        user_password = request.POST.get("userPassWord")
        user  = auth.authenticate(username=user_name,password=user_password)

        # if user_name == "lzjian" and user_password == "4399uxw":
        #     HttpResponse = HttpResponseRedirect("/toEventManage/")  # 登陆成功重定向至签到管理页面
        #     # HttpResponse.set_cookie('showUserName', user_name, 3600)  # 设置cookie时间为3600秒
        #     request.session['showUserName'] = user_name  # 将session信息记录到浏览器
        #     return HttpResponse

        if user is not None:
            auth.login(request, user)  # 登陆
            request.session['showUserName'] = user_name  # 将session信息记录到浏览器
            HttpResponse = HttpResponseRedirect("/toEventManage/")  # 登陆成功重定向至签到管理页面
            return HttpResponse

        else:
            return render(request, 'index.html', {'error': '用户名或密码错误!'})  # 登陆失败返回主页页面并返回error信息


# 跳转至签到管理页面
@login_required()
def toEventManage(request):
    # user_name = request.COOKIES.get('showUserName', '')  # 读取浏览器cookie
    user_name = request.session.get('showUserName', '')  # 读取浏览器session
    return render(request, "eventManage.html", {"showUserName": user_name})
